//
//  KeHuListViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/9.
//

#import "KeHuListViewController.h"
#import "KeHuListTableViewCell.h"
#import "KeHuInfoModel.h"

#import "LXCustomerDeatilViewController.h"
@interface KeHuListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic,strong)  UITableView       *  tableView;
@property (nonatomic, strong) NSMutableArray    *  dataAry;
@property (nonatomic, assign) NSInteger            pageIndex;
@property(nonatomic,strong)NSString   *searchStr;
@end

@implementation KeHuListViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
    self.searchStr = @"";
    
    self.pageIndex = 1;
    
    [self loadData];
}

- (void)viewDidLoad {
     [super viewDidLoad];
    
    self.view.backgroundColor = ColorWithF5F5F5;
    
    [self.view addSubview:self.tableView];
   
   BD_WEAKSELF
   MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       weakSelf.pageIndex = 1;
       [self loadData];
   }];

   header.lastUpdatedTimeLabel.hidden = YES;
   self.tableView.mj_header = header;
   self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
       self.pageIndex++;
       [self loadData];
   }];
   
   [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.size.mas_equalTo(CGSizeMake(ScreenWidth, kScreenHeight-StatusBarHeight-100-65));
       make.left.equalTo(self.view.mas_left).offset(0);
       make.right.equalTo(self.view.mas_right).offset(0);
       make.top.equalTo(self.view.mas_top).offset(5);
   }];
    
    
    [[kNotifyCenter rac_addObserverForName:@"customerSearchText" object:nil] subscribeNext:^(NSNotification * _Nullable note) {
        self.searchStr= [NSString stringWithFormat:@"%@",note.object];
        [self loadData];
    }];
    
}
-(void)loadData{

   
    NSMutableDictionary *dic = @{
        @"type":@(self.selectIndex),
        @"page":@(self.pageIndex),
        @"rows":@(10)
    }.mutableCopy;
        
    if (!StringIsEmpty(self.searchStr)) {
        [dic setValue:self.searchStr forKey:@"keyWords"];
    }
    
    [MSNetworkManager postRevertUrl:POST_ListWithSign_URL params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        [self endRefreshing];
        
        if ([self.tableView.mj_header isRefreshing]||self.pageIndex==1) {
            [self.dataAry removeAllObjects];
            [self.tableView.mj_footer resetNoMoreData];
        }
        NSInteger totalPage = [resonseObj[@"total"] integerValue];
            
        NSArray *records = resonseObj[@"list"];
        
        [self.dataAry addObjectsFromArray:[KeHuInfoModel  mj_objectArrayWithKeyValuesArray:records]];
        
        
        if (self.dataAry.count>=totalPage) {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        else {
            self.tableView.mj_footer.state = MJRefreshStateIdle;
        }
        
            
        [self.tableView reloadData];

       
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self endRefreshing];
    } withShowHud:YES];

    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  self.dataAry.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger index = 0;
    static NSString *identifier = @"";
    
    KeHuInfoModel *model= self.dataAry[indexPath.section];

    if (model.signType == 0) {
        identifier = @"KeHuListTableViewCell1";
        index = 0;
        
    }
    else {
        identifier = @"KeHuListTableViewCell2";
        index = 1;
    }

    
    KeHuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([KeHuListTableViewCell class]) owner:self options:nil] objectAtIndex:index];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (model.signType == 0) {
        cell.isDelete = YES;
    }
    else {
        cell.isDelete = NO;
    }
    
    if (model.signState == 0) {
        cell.notSignModel = model;
    }
    else {
        cell.signedModel = model;
    }
    // 删除操作
    [cell setToSend:^{
       
        
        if (model.saleOrRentType==1||model.saleOrRentType==2) {
            [Tool showAlertWithTitle:@"温馨提示" message:@"当前用户已租/已购车, 无法进项删除操作!"];
            return;
        }
        
        [Tool showAlertTitle:@"温馨提示" msg:@"是否确认删除改用户?" cancelTitle:@"取消" commitBtnTitle:@"确认" cancelHandlerBlock:^{
            
        } commitHandlerBlock:^{
            NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
            [params setObject:model.ID forKey:@"id"];
            
            
            [MSNetworkManager postRevertUrl:kDeleteCustomer_URL params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
                if (isSuccess){
                    showAlert(@"删除成功");
                    [self.tableView.mj_header beginRefreshing];
                }
                
            } failure:^(NSUInteger code, NSString * _Nonnull message) {
                
            } withShowHud:YES];
        } onVC:self];
        
    }];
    
    
    
   
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LXCustomerDeatilViewController *vc = [[LXCustomerDeatilViewController alloc] init];
    KeHuInfoModel *model= self.dataAry[indexPath.section];
    vc.beginTime = model.beginTime;
    vc.endTime = model.endTime;
    vc.ID = model.ID;
    [self pushToNextController:vc];
    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self loadData];
    [textField resignFirstResponder];
    return YES;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.estimatedRowHeight = 58;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 10;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ColorWithF5F5F5;
    }
    return _tableView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KeHuInfoModel *model= self.dataAry[indexPath.section];
    if (model.signType != 0) {
        return UITableViewAutomaticDimension;
    }
    return kComHeight;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    view.backgroundColor = ColorWithF5F5F5;
    return view;
}
- (NSMutableArray *)dataAry {
    if (!_dataAry) {
        self.dataAry = [NSMutableArray array];
    }
    return _dataAry;
}
#pragma mark - ------------------ DZNEmptyData ------------------
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"No_order_icon"];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (!self.tableView.mj_header.isRefreshing && !self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer resetNoMoreData];
         self.pageIndex = 1;
        [self loadData];
    }
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50;
}
- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
@end
